from fastapi import Form
from fastapi import Request
from psycopg.errors import UniqueViolation, ForeignKeyViolation
from starlette.responses import RedirectResponse

from .config import app, view_page
from .config import dblock
from .error_view import redirect_error


# from .error_view import redirect_error


@app.get("/class")
async def classs(request: Request):
    # with dblock() as db:
    #     db.execute("""
    #     SELECT sn AS stu_sn, name as stu_name FROM student ORDER BY name
    #     """)
    #     students = list(db)
    return view_page(request, "class_add.html")


@app.post("/class/add")
async def action_class_add(
        cou_sn: int = Form(...), cla_name: str = Form(...), semester: str = Form(...),
        location: str = Form(...)
        # stu_sn: int = Form(...), cla_sn: int = Form(...)
):
    try:
        with dblock() as db:
            db.execute(
                """
                INSERT INTO course_class (cou_sn, cla_name,semester,location) 
                VALUES (%(cou_sn)s, %(cla_name)s, %(semester)s, %(location)s)
                """,
                dict(cou_sn=105, cla_name=cla_name, semester=semester, location=location),
            )
    except UniqueViolation:
        return redirect_error(f"学生{cla_name}的课程{cou_sn}成绩已添加", return_path="/")
    except ForeignKeyViolation as ex:
        return redirect_error(f"无此学生或课程: {ex}", return_path="/")

    return RedirectResponse(url="/", status_code=302)
